import { defineStore } from 'pinia'
import { ref, computed, onMounted } from 'vue'
import { getProducts, buyProducts } from '../api/product'
import { ElMessage } from 'element-plus'

// 创建并导出store
export const useShoppingCarStore = defineStore('carStore', () => {
  // 定义商品列表
  const productList = ref([])
  // 获取数据
  onMounted(() => {
    getProducts().then((res) => {
      productList.value = res
    })
  })
  // 定义购物车列表
  const shopList = ref([])
  // 定义购物车总价计算
  const totalPrice = computed(() => {
    return shopList.value.reduce((total, item) => total + item.price * item.count, 0)
  })

  // 添加商品到购物车,传入单个商品对象信息
  const addProduct = (product) => {
    if (product.number === 0) {
      ElMessage.error('商品售罄')
      return
    } else {
      product.number--
      const index = shopList.value.findIndex((item) => item.id === product.id)
      if (index === -1) {
        shopList.value.push({
          id: product.id,
          title: product.title,
          price: product.price,
          count: 1
        })
      } else {
        shopList.value[index].count++
      }
      // 购物车排序
      shopList.value.sort((a, b) => b.count - a.count)
    }
  }
  // 结算
  const buyProduct = () => {
    buyProducts().then((res) => {
      if (res) {
        ElMessage.success('结算成功')
        shopList.value = []
      } else {
        ElMessage.error('结算失败')
      }
    })
  }

  return {
    productList,
    shopList,
    totalPrice,
    addProduct,
    buyProduct
  }
})
